<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/4/19 0019
 * Time: 上午 10:30
 */
class Ucenter  extends Base_Controller
{
    private $user_id;

    private  $page_limit = 4;

    public function __construct()
    {
        parent::__construct();
        $this->load->model('userv2info_model');
        $this->load->model('userv2_model');
        $this->load->model('apporder_model');
        $this->load->model('userv2mobile_model');
        $this->load->library('Myusersubscribe');
        $this->load->library('Mysms');
        $this->load->helper('captcha');
        $this->user_id = 1;
        session_start();
    }

    /**
     * 用户注册
     */
    public function userreg()
    {
        $password = isset($_POST['password']) && strlen($_POST['password'])? $_POST['password'] : null;
        $re_password = isset($_POST['re_password']) && strlen($_POST['re_password'])? $_POST['re_password'] : null;
        if($re_password != $password) $this->error('两次密码输入的不一样');

        if(isset($_POST['way']) && $_POST['way'] == 'email'){
            $email = isset($_POST['email']) && strlen($_POST['email']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ? $_POST['email'] : null;
            $securimage_code_value = isset($_POST['securimage_code_value']) && strlen($_POST['securimage_code_value'])? $_POST['securimage_code_value'] : null;
            if(!check_securimage_code_value($securimage_code_value)) $this->error('验证码错误');
            if($email === null) $this->error('邮箱格式不正确');
            if($this->userv2_model->getUserv2(array('userId' => $email, 'utype' => 'TOURIST'))) $this->error('该邮箱已经注册过');

            $data = array(
                'source'     => 'WAP',
                'userId'     => $email,
                'email'     => $email,
                'userName'   => '新用户',
                'userToken'  => md5($password),
                'userIcon'   => '/resource/skin/img/index_mingxing.png',
                'userGender' => NULL,
                'status'     => 1,
                'created'    => time(),
                'changed'    => time(),
                'utype'      => 'TOURIST',
            );
            $uid = $this->userv2_model->createUser($data);
            if($uid > 0){
                $mail_data = $this->myusersubscribe->user_activation($uid,$email,$data['created'],$mail_type='tourist');
                $this->userv2info_model->createUserV2Info(array('uid' => $uid));
                $status = $mail_data['status'];
                if(!$status){
                    $this->error('注册错误，请重试');
                }else{
                    $this->success(array('url' => $mail_data['url']));
                }
            }else{
                $this->error('注册错误，请重试');
            }
        }else{
            $phone = isset($_POST['phoneNum']) && strlen($_POST['phoneNum']) ? $_POST['phoneNum'] : null;
            $areaCode = isset($_POST['areaCode']) && strlen($_POST['areaCode']) ? ltrim($_POST['areaCode'], '+') : null;
            $securimage_code_value = isset($_POST['securimage_code_value']) && strlen($_POST['securimage_code_value'])? $_POST['securimage_code_value'] : null;
            $smsCode = $this->userv2mobile_model->getSmsCode(array('mobile' => '+'.$areaCode.$phone));

            if(!$smsCode || $smsCode['code'] != $securimage_code_value) $this->error('验证码不正确!');
            if($this->userv2_model->getUserv2(array('telNum' => $phone, 'utype' => 'TOURIST'))) $this->error('该手机号已经注册过');
            $data = array(
                'source'     => 'WAP',
                'telNum'     => $phone,
                'userName'   => '新用户',
                'userToken'  => md5($password),
                'userIcon'   => '/resource/skin/img/index_mingxing.png',
                'userGender' => NULL,
                'status'     => 1,
                'telActive'  => 1,
                'active'     => 1,
                'created'    => time(),
                'changed'    => time(),
                'telCode'    => $areaCode,
                'utype'      => 'TOURIST',
            );
            $uid = $this->userv2_model->createUser($data);
            if($uid > 0){
                $this->userv2info_model->createUserV2Info(array('uid' => $uid, 'userPhone' => "+".$areaCode.trim($phone)));

                $this->success();
            }else{
                $this->error('注册错误，请重试');
            }
        }
    }

    /**
     * 玩伴注册
     */
    public function guiderreg()
    {
        $password = isset($_POST['password']) && strlen($_POST['password'])? $_POST['password'] : null;
        $re_password = isset($_POST['re_password']) && strlen($_POST['re_password'])? $_POST['re_password'] : null;
        $email = isset($_POST['email']) && strlen($_POST['email']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ? $_POST['email'] : null;
        $phone = isset($_POST['phoneNum']) && strlen($_POST['phoneNum']) ? $_POST['phoneNum'] : null;
        $areaCode = isset($_POST['areaCode']) && strlen($_POST['areaCode']) ? ltrim($_POST['areaCode'], '+') : null;
        $securimage_code_value = isset($_POST['securimage_code_value']) && strlen($_POST['securimage_code_value'])? $_POST['securimage_code_value'] : null;
        $userFamily = isset($_POST['xing']) && strlen($_POST['xing'])? $_POST['xing'] : null;
        $userName = isset($_POST['ming']) && strlen($_POST['ming'])? $_POST['ming'] : null;
        $userGender = isset($_POST['sex']) && strlen($_POST['sex'])? $_POST['sex'] : null;

        $smsCode = $this->userv2mobile_model->getSmsCode(array('mobile' => '+'.$areaCode.$phone));

        if(!$smsCode || $smsCode['code'] != $securimage_code_value) $this->error('验证码不正确!');
        if($this->userv2_model->getUserv2(array('telNum' => $phone, 'utype' => 'GUIDER'))) $this->error('该手机号已经注册过');
        if($this->userv2_model->getUserv2(array('userId' => $email, 'utype' => 'GUIDER'))) $this->error('该邮箱已经注册过');
        if($re_password != $password) $this->error('两次密码输入的不一样');
        if(!$userFamily || !$userName || !$userGender) $this->error('姓名、性别不能为空');

        $data = array(
            'source'     => 'WAP',
            'userId'     => $email,
            'userName'   => '新用户',
            'userToken'  => md5($password),
            'userName' => $userFamily.$userName,
            'userGender' => $userGender,
            'userIcon'   => '/resource/skin/img/index_mingxing.png',
            'telActive'  => 1,
            'status'     => 1,
            'created'    => time(),
            'changed'    => time(),
            'utype'      => 'GUIDER',
        );
        $uid = $this->userv2_model->createUser($data);
        if($uid > 0){
            $mail_data = $this->myusersubscribe->user_activation($uid,$email,$data['created'],$mail_type='guider');
            $this->userv2info_model->createUserV2Info(array('uid' => $uid, 'userPhone' => "+".$areaCode.trim($phone)));
            $status = $mail_data['status'];
            if(!$status){
                $this->error('注册错误，请重试');
            }else{
                $this->success(array('url' => $mail_data['url']));
            }
        }else{
            $this->error('注册错误，请重试');
        }
    }

    /**
     * 登录
     */
    public function login()
    {
        $uType = isset($_POST['utype']) && strlen($_POST['utype']) ? strtoupper($_POST['utype']) : 'TOURIST';
        $phone = isset($_POST['phoneNum']) && strlen($_POST['phoneNum']) ? $_POST['phoneNum'] : null;
        $password = isset($_POST['password']) && strlen($_POST['password'])? $_POST['password'] : null;
        if(!$phone || !$password) $this->error('账号、密码不能为空！');
        $res = $this->userv2_model->checkUser($phone, $uType);
        if($res && $res['active'] == 1){
            if(!isset($_SESSION)) session_start();
            $_SESSION['uid'] = $res['uid'];
            $_SESSION['user_type'] = $res['utype'];
            $_SESSION['is_login'] = 1;
            $this->success('登录成功');
        }else{
            if(!$res){
                $this->error('你输入的密码或是邮箱地址/手机号码错误，请重新输入');
            }else{
                $this->error('请先激活邮箱');
            }
        }
    }

    /**
     * 退出
     */
    public function logout()
    {
        if(!isset($_SESSION)) session_start();
        $_SESSION['uid'] = array();
        $_SESSION['user_type'] = array();
        $_SESSION['is_login'] = array();
        unset($_SESSION);

        $this->success();
    }

    /**
     * 验证token
     */
    public function confirm_token()
    {
        $token = isset($_GET['token']) && strlen($_GET['token']) ? $_GET['token'] : null;
        if($token == null) $this->error('token 不能为空');
        list($status, $msg) = $this->myusersubscribe->confirm_token($token);
        if($status == 1){
            $this->success();
        }elseif($status == 2){
            $this->error($msg);
        }else{
            $this->error($msg);
        }
    }

    /**
     * 验证码
     */
    public function checkcode()
    {

        $vals = array(
            'word'       => rand(1000, 10000),
            'img_width'  => '80',
            'img_height' => '30',
            'expiration' => 7200
        );
        create_captcha($vals);
    }

    /**
     * 发送短信
     */
    public function sendmsg(){
        $utype = isset($_POST['utype']) && strlen($_POST['utype']) ? $_POST['utype'] : null;
        $phone = isset($_POST['phoneNum']) && strlen($_POST['phoneNum']) ? $_POST['phoneNum'] : null;
        $areacode = isset($_POST['areaCode']) && strlen($_POST['areaCode']) ? $_POST['areaCode'] : null;
        $code = mt_rand(0,9).mt_rand(0,9).mt_rand(0,9).mt_rand(0,9).mt_rand(0,9).mt_rand(0,9);
        $data['mobile'] = '+'.$areacode.$phone;
        $data['code'] = $code;
        $data['created'] = time();
        $smsCode = $this->userv2mobile_model->getSmscode(array('mobile' => '+'.$areacode.$phone));
        if(!$phone || !$areacode) $this->error('电话号码、区域号不能为空');
        if($smsCode && ($smsCode['created']+60) >= time()) $this->error('短信发送时间还未过一分钟，请稍后再发！');
        $id = $this->userv2mobile_model->addSmsCode($data);

        if($id>0){
            if($utype=="TOURIST"){
                $tpl_id = 1330065;
                $tpl_value = "#code#={$code}";
                $rs = $this->mysms->send_sms_to_user_id($tpl_id, $tpl_value, $phone);
            }else{
                $tpl_id = 1129805;
                $tpl_value = "#code#={$code}";
                $rs = $this->mysms->send_sms_to_user_id($tpl_id, $tpl_value, $phone);
            }
            $rs = json_decode($rs,true);
            if($rs['code'] == 0){
               $this->success();
            }

        }
        $this->error();

    }

    public function openlogin()
    {
        $this->load->library('Myweibo');
        exit($this->myweibo->get_login_url());
    }

    public function action_callback($type)
    {
        $query = $this->request->query();
        $access_token = OpenLogin::instance($type)->get_access_token();
        if (empty($access_token))
        {
            $this->msg('获取授权出错', '/');
        }
        $openid = OpenLogin::instance()->get_openid($access_token);
        if (empty($openid))
        {
            $this->msg('获取用户出错', '/');
        }

        $user = OpenLogin::instance()->get_user_info($openid, $access_token);

        if (empty($user))
        {
            $this->msg('获取用户信息出错');
        }
        $user['type'] = $type;
        $user['utype'] = Arr::get($query,'type');

        OpenLogin::login($user);
        $this->msg('', '/');
    }

}